package com.ys.service.finance.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.dto.AddDto;
import com.ys.entity.finance.TcwDepositPlatform;
import com.ys.entity.finance.TcwWanliFinance;
import com.ys.entity.sys.TbStaticConfig;
import com.ys.entity.sys.YsCol;
import com.ys.enume.finance.TcwExchangeRateEnum;
import com.ys.enume.wanli.WfSubUserEnum;
import com.ys.mapper.finance.FinanceMapper;
import com.ys.mapper.finance.TcwWanliFinanceMapper;
import com.ys.service.finance.TcwWanliFinanceService;
import com.ys.util.CheckUtil;
import com.ys.util.wanli.WanliUtils;
import com.ys.vo.ApiResponse;
import com.ys.vo.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 万里汇账号资金
 */
@Service("tcwWanliFinanceService")
public class TcwWanliFinanceServiceImpl implements TcwWanliFinanceService {
	private static final Logger logger = LoggerFactory.getLogger(TcwWanliFinanceServiceImpl.class);

	@Autowired
	private TcwWanliFinanceMapper tcwWanliFinanceMapper;

	@Autowired
	private CheckUtil checkUtil;

	@Autowired
	private FinanceMapper financeMapper;

	/**
	 * 新增
	 */
	@Override
	public R add(Map<String, Object> params, Long menuId) throws Exception{
		logger.info("新增传参:"+params);
		//参数验证
		String errorBack = checkParams(params, menuId);
		if(errorBack!=null && !"".equals(errorBack)){
			return R.error(errorBack);
		}
		TcwWanliFinance tcwWanliFinance = JSON.parseObject(JSON.toJSONString(params), TcwWanliFinance.class);

		//根据币种循环新增
		for (TcwExchangeRateEnum.ExchangeRate e : TcwExchangeRateEnum.ExchangeRate.values()) {
			tcwWanliFinance.setExchangeRateCode(e.value);
			tcwWanliFinance.setStatus(1);
			tcwWanliFinance.setSystemSum(BigDecimal.ZERO);
			tcwWanliFinance.setPurchaseType(0);
			//新增
			tcwWanliFinanceMapper.insert(tcwWanliFinance);
		}

		//return R.ok(EditDto.closeAndReload());
		return R.ok(AddDto.gotoEdit("/web/finance/tcwWanliFinance/toEdit?id=" + tcwWanliFinance.getId()));
	}


	/**
	 * 修改
	 */
	@Override
	public R update(Map<String, Object> params, Long menuId) throws Exception{
		logger.info("修改传参:"+params);
		//参数验证
		String errorBack = checkParams(params, menuId);
		if(errorBack!=null && !"".equals(errorBack)){
			return R.error(errorBack);
		}
		TcwWanliFinance tcwWanliFinance = JSON.parseObject(JSON.toJSONString(params), TcwWanliFinance.class);

		tcwWanliFinanceMapper.update(tcwWanliFinance);
		return R.ok();
	}


	/**
	 * 参数验证
	 */
	public String checkParams(Map<String, Object> params, Long menuId) throws Exception {
		//获取pc字段数据
		List<YsCol> listField = new YsCol()
				.where("A.MenuId = "+menuId)
				.setOrderby("A.SortNo ASC")
				.queryList();
		//验证必填字段的非空；其他字段的长度限制、类型
		String backMsg = checkUtil.checkTableColLengthAndDataType("TCW_WanliFinance",listField,params,ysColItem->ysColItem.getFormEditRequired()!=null && ysColItem.getFormEditRequired() == 1);
		return backMsg;
	}


	/**
	 * 可调用inquiryBalance接口查询账户余额。
	 */
	@Override
	public ApiResponse inquiryBalance() {
		ApiResponse apiResponse = new ApiResponse();
		JSONArray accountBalances;
		JSONObject accountBalance;
		JSONObject totalBalance;
		String currency = "";
		BigDecimal amount = BigDecimal.ZERO;
		try {
			apiResponse.setCode(0);
			apiResponse.setMessage("获取成功!");
			String content = "";

			//查询万里汇莫程账号MID
			TbStaticConfig tbStaticConfig = new TbStaticConfig()
					.setKeyOne("wanli-mid")
//					.setKeyTwo("wanli-mid-mc");
					.setKeyTwo("wanli-mid-cs")
					.queryFirst();

			//查询万里汇莫程账号clientId
			TbStaticConfig tbStaticConfigClientId = new TbStaticConfig()
					.setKeyOne("wanli-mid")
					.setKeyTwo("wanli-mid-clientId")
					.queryFirst();

			String httpMethod = WfSubUserEnum.Type.POST.value;
			//主账号有子账号
			String clientId = tbStaticConfigClientId.getName();
			String uriWithQueryString = WfSubUserEnum.Type.INQUIRYBALANCE.value;
			String connectedCustomerId = tbStaticConfig.getName();

			String result = WanliUtils.result(content, httpMethod, uriWithQueryString, clientId,connectedCustomerId);
			JSONObject resultJO = JSON.parseObject(result);
			JSONObject resultState = JSON.parseObject(resultJO.get("result").toString());
			//判断是否成功
			if (!resultState.get("resultStatus").toString().equals(WfSubUserEnum.Type.S.value)){
				apiResponse.setCode(500);
				apiResponse.setMessage(resultState.get("resultMessage").toString());
				return apiResponse;
			}

			accountBalances = JSON.parseArray(resultJO.get("accountBalances").toString());
			for (int i = 0; i < accountBalances.size(); i++) {
				accountBalance = JSON.parseObject(accountBalances.get(i).toString());
				totalBalance = JSON.parseObject(accountBalance.get("totalBalance").toString());
				currency = totalBalance.get("currency").toString();
				if (!currency.equals("JPY")){
					//获取的金额是100:1
					amount = new BigDecimal(totalBalance.get("value").toString()).divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP);
				}else {
					amount = new BigDecimal(totalBalance.get("value").toString());
				}


				//查询mid平台
				TcwDepositPlatform tcwDepositPlatform = new TcwDepositPlatform().setMid(tbStaticConfig.getName()).queryFirst();
				if (tcwDepositPlatform != null){
					//查询万里汇账户资金数据将金额赋值
					TcwWanliFinance tcwWanliFinance = new TcwWanliFinance().setExchangeRateCode(currency).setDepositPlatformCode(tcwDepositPlatform.getCode()).queryFirst();
					if (tcwWanliFinance != null) {
						tcwWanliFinance.setApiSum(amount);
					}else {
						//填充至其他金额
						tcwWanliFinance = new TcwWanliFinance().setExchangeRateCode("OTHER").setDepositPlatformCode(tcwDepositPlatform.getCode()).queryFirst();
						if (tcwWanliFinance != null){
							if (tcwWanliFinance.getApiSum() == null){
								tcwWanliFinance.setApiSum(amount);
							}else {
								tcwWanliFinance.setApiSum(tcwWanliFinance.getApiSum().add(amount));
							}
						}
					}
					tcwWanliFinance.setAccountTime(new Date());
					tcwWanliFinanceMapper.update(tcwWanliFinance);
				}

			}
		}catch (Exception e){
			apiResponse.setCode(500);
			apiResponse.setMessage(e.getMessage());
			return apiResponse;
		}
		return apiResponse;

	}


}
